import { message } from 'antd';

import type { Effect } from '@@/plugin-dva/connect';
import type { ImmerReducer } from 'umi';

import { registerUser, sendSms, loginUser, userInfo } from '@/services/login';
import type { SysUserDto } from '@/types/User';
import { getErrorMsg } from '@/util/utils';

export const namespace = 'GLOBAL_DATA';

export interface IReduxState {
  currentMenu?: string;
  userInfo?: SysUserDto;
}

export interface IReduxStore {
  namespace: 'GLOBAL_DATA';
  state: IReduxState;
  effects: {
    register: Effect;
    sendSmsCode: Effect;
    login: Effect;
    getUserInfo: Effect;
  };
  reducers: {
    save: ImmerReducer<IReduxState, { type: string; payload?: any }>;
    setCurrentMenu: ImmerReducer<IReduxState, { type: string; payload?: string }>;
  };
}
const reduxStore: IReduxStore = {
  namespace,
  state: {},
  effects: {
    *sendSmsCode({ payload, callback }, { call }) {
      try {
        const res = yield call(sendSms, payload);
        callback(res);
      } catch (error) {
        console.log(error);
      }
    },
    *register({ payload, callback }, { call }) {
      try {
        const res = yield call(registerUser, payload);
        callback(res);
      } catch (error) {
        console.log(error);
      }
    },
    *getUserInfo({ payload, callback }, { call, put }) {
      try {
        const res = yield call(userInfo, payload);
        if (res.code === 200) {
          callback();
          localStorage.setItem('USER_INFO', JSON.stringify(res?.data));
          yield put({
            type: 'save',
            payload: {
              userInfo: {
                ...res?.data,
              },
            },
          });
        } else {
          message.error(getErrorMsg(res));
        }
      } catch (error) {
        console.log(error);
      }
    },
    *login({ payload, callback, callbackLoading }, { call, put }) {
      try {
        const res = yield call(loginUser, payload);
        if (res.code === 200) {
          yield put({
            type: 'save',
            payload: {
              userLoginInfo: {
                ...res?.data,
                // 秒换算成天数
                expire: res.data?.expire / 86400,
              },
            },
          });
          localStorage.setItem('refreshToken', res.data.refreshToken);
          callback(res);
        } else {
          message.error(getErrorMsg(res));
          callbackLoading();
        }
      } catch (error) {
        console.log(error);
      }
    },
  },
  reducers: {
    save(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    setCurrentMenu: (state, { payload }) => {
      return {
        ...state,
        currentMenu: payload,
      };
    },
  },
};
export default reduxStore;
